import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import org.dbunit.database.DatabaseConnection;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.database.QueryDataSet;
import org.dbunit.dataset.xml.FlatDtdDataSet;
import org.dbunit.dataset.xml.FlatXmlWriter;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableAutoConfiguration
public class DBUnitExportTables {
    public static void main(String[] args) throws Exception {
        // database connection
        Connection jdbcConnection = DriverManager.getConnection(
                "jdbc:postgresql://localhost:5432/hello",
                "postgres",
                "postgres");
        IDatabaseConnection connection = new DatabaseConnection(jdbcConnection);

        QueryDataSet queryDataSet = new QueryDataSet(connection);

        // Requêtes de sélection

        String nomTable = "my_user";
        queryDataSet.addTable(nomTable, "select * from "+nomTable+"");

        // Export
        String fileNameExport = "data";
        String dirExport = "target/generated";
        (new File(dirExport)).mkdirs();

        // DTD
        FlatDtdDataSet.write(queryDataSet, new FileOutputStream(dirExport+"/"+fileNameExport+".dtd"));

        // XML
        FlatXmlWriter datasetWriter = new FlatXmlWriter(new FileOutputStream(dirExport+"/"+fileNameExport+".xml"));
        datasetWriter.setDocType(fileNameExport+".dtd");
        datasetWriter.write(queryDataSet);
        System.out.println("Finish !");
    }

}